-- Thread
-- 多线程库

Thread = {}
Thread.Main = 0

Thread.runningThread = Thread.Main

-- 将一个函数创建为线程，返回一个函数，用于调用此线程
function Thread.create(func,errorHander)
    local thread = coroutine.create(func)
    return function(...)
        return Thread.run(thread,errorHander,...)
    end
end

-- 内部函数，调用线程
function Thread.run(thread,errorHander,...)
    if Thread.running == thread then
        return
    end
    if coroutine.status(thread) == "dead" then
        print("[" .. tostring(thread) .. "] " .. " Has Dead!")
        
        return
    end
    local UpThread = Thread.runningThread
    Thread.runningThread = thread
    local t = {coroutine.resume(thread,...)}
    Thread.runningThread = UpThread
    if t[1] == false then
        print("[" .. tostring(thread) .. "] Error:" .. (t[2] or "(null)"))
        if errorHander then
            errorHander(thread,t[2])
        else
            error("[" .. tostring(thread) .. "] Error:" .. (t[2] or "(null)"))
        end
        return
    end
    table.remove(t,1)
    return table.unpack(t)
end

-- 线程内调用函数，暂停线程
function Thread.wait(...)
    if Thread.runningThread ~= Thread.Main then
        return coroutine.yield(...)
    end
end

-- 取当前正在运行线程
function Thread.running()
    return coroutine.running()
end

-- 在游戏时暂停线程
function Thread.waitWhenGaming(...)
    if GameState == Gaming then
        if Thread.runningThread ~= Thread.Main then
            return coroutine.yield(...)
        end
    end
end
